package com.myblog.demo.controller;

import com.myblog.demo.common.AjaxResult;
import com.myblog.demo.common.UserSessionTools;
import com.myblog.demo.entity.UserInfo;
import com.myblog.demo.entity.vo.CommentInfoVO;
import com.myblog.demo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    /**
     * 查询指定文章下面的评论
     * @param aid 文章id
     * @return AjaxResult
     */
    @RequestMapping("/getcomments")
    public AjaxResult getComments(Integer aid){
        // 参数合法性判断
        if(aid == null || aid <= 0){
            return AjaxResult.fail(-1, "参数错误！");
        }

        // 查询数据库
        List<CommentInfoVO> list = commentService.getCommentsList(aid);

        return AjaxResult.success(list);
    }

    /**
     * 添加评论
     * @param aid 文章id
     * @param content 评论内容
     * @param request 获取当前用户
     * @return AjaxResult
     */
    @RequestMapping("/add")
    public AjaxResult addComment(Integer aid, String content, HttpServletRequest request){
        // 参数合法性判断
        System.out.println(aid);
        System.out.println(content);
        if(aid == null || aid <= 0 || !StringUtils.hasLength(content)){
            return AjaxResult.fail(-1, "参数错误！");
        }

        // 获取当前登录用户
        UserInfo loginUser = UserSessionTools.getLoginUser(request);
        if(loginUser == null){
            return AjaxResult.fail(-2, "当前用户未登录！");
        }

        int uid = loginUser.getId();

        // 持久化
        int result = commentService.addComment(uid, aid, content);

        return AjaxResult.success(result);
    }

    /**
     * 通过id删除评论
     * @param id 评论id
     * @param request 用于获取用户id
     * @return AjaxResult
     */
    @RequestMapping("/delbyid")
    public AjaxResult delCommentById(Integer id, Integer aid, HttpServletRequest request){
        // 参数合法性判断
        if(id == null || id <= 0 || aid == null || aid <= 0){
            return AjaxResult.fail(-1, "参数错误！");
        }

        // 获取当前登录用户
        UserInfo loginUser = UserSessionTools.getLoginUser(request);
        if(loginUser == null){
            return AjaxResult.fail(-2, "当前用户未登录！");
        }

        int uid = loginUser.getId();

        int result = commentService.delCommentById(id, uid, aid);
        return AjaxResult.success(result);
    }
}
